import React, { useEffect, useState, useCallback, useRef } from 'react';
import { View, Text, SafeAreaView, Image, TouchableOpacity, ScrollView, TextInput, Modal, Animated } from 'react-native';
import { DatePicker } from '@ant-design/react-native';
import { styles } from './styles';
import { searchUserTaskApi } from './api';
import PortalDropdown from '../../../../components/PortalDropdown';

interface ProductionTasksProps {
    onBackPress?: () => void;
}

interface TaskRecord {
    id: string;
    work_order_num: string;
    batch_order_num: string;
    product_short_name: string;
    product_model: string;
    product_specs: string;
    product_encode: string;
    product_link: string | null;
    process_name: string;
    work_start: string;
    work_end: string;
    quantity: number;
    state: number;
}

const ProductionTasks: React.FC<ProductionTasksProps> = ({ onBackPress }) => {
    // 搜索条件状态
    const [searchParams, setSearchParams] = useState({
        current: 1,
        size: 10,
        work_order_num: '',
        search_start: '',
        search_end: '',
        state: ''
    });

    // 数据状态
    const [taskRecords, setTaskRecords] = useState<TaskRecord[]>([]);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        size: 10,
        total: 0,
        pages: 0
    });

    // 日期选择器状态
    const [startDate, setStartDate] = useState<Date | undefined>(undefined);
    const [endDate, setEndDate] = useState<Date | undefined>(undefined);

    // 状态选择器状态
    const [selectedState, setSelectedState] = useState('');
    const [stateDropdownVisible, setStateDropdownVisible] = useState(false);
    const [stateArrowRotation] = useState(new Animated.Value(0));

    // Portal 下拉框的 ref
    const stateTriggerRef = useRef<View>(null);

    // 图片预览相关状态
    const [showImageModal, setShowImageModal] = useState(false);
    const [previewImageUrl, setPreviewImageUrl] = useState('');

    // 状态选项
    const stateOptions = [
        { value: '0', label: '初始化' },
        { value: '1', label: '生产中' },
        { value: '2', label: '已完成' }
    ];

    // 获取任务列表
    const fetchTaskList = useCallback(async (params: any) => {
        try {
            setLoading(true);
            const response = await searchUserTaskApi(params);

            if (response.code === 200) {
                setTaskRecords(response.data.records || []);
                setPagination({
                    current: response.data.current || 1,
                    size: response.data.size || 10,
                    total: response.data.total || 0,
                    pages: response.data.pages || 0
                });
            } else {
                console.error('获取任务列表失败:', response.msg);
            }
        } catch (error) {
            console.error('获取任务列表失败:', error);
        } finally {
            setLoading(false);
        }
    }, []);

    // 组件挂载时获取数据
    useEffect(() => {
        fetchTaskList({
            current: 1,
            size: 10
        });
    }, [fetchTaskList]);

    // 处理搜索
    const handleSearch = () => {
        const params = {
            ...searchParams,
            current: 1,
            search_start: startDate ? formatDate(startDate) : '',
            search_end: endDate ? formatDate(endDate) : '',
            state: selectedState
        };
        setSearchParams(params);
        fetchTaskList(params);
    };

    // 处理重置
    const handleReset = () => {
        setSearchParams({
            current: 1,
            size: 10,
            work_order_num: '',
            search_start: '',
            search_end: '',
            state: ''
        });
        setStartDate(undefined);
        setEndDate(undefined);
        setSelectedState('');
        fetchTaskList({
            current: 1,
            size: 10
        });
    };

    // 处理分页变化
    const handlePageChange = (page: number) => {
        const params = {
            ...searchParams,
            current: page
        };
        setSearchParams(params);
        fetchTaskList(params);
    };

    // 格式化日期
    const formatDate = (date: Date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    // 获取状态显示文本
    const getStateText = (state: number) => {
        switch (state) {
            case 0: return '初始化';
            case 1: return '生产中';
            case 2: return '已完成';
            default: return '-';
        }
    };

    // 获取状态下拉显示文本
    const getStateDisplayText = () => {
        if (!selectedState) return '状态';
        const state = stateOptions.find(opt => opt.value === selectedState);
        return state ? state.label : '状态';
    };

    // 切换状态下拉框显示状态
    const toggleStateDropdown = () => {
        const toValue = stateDropdownVisible ? 0 : 1;
        setStateDropdownVisible(!stateDropdownVisible);

        Animated.timing(stateArrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 处理图片预览
    const handlePreviewImage = (imageUrl: string | null) => {
        if (imageUrl) {
            setPreviewImageUrl(imageUrl);
        } else {
            // 如果没有图片，使用默认图片
            setPreviewImageUrl('../../../../assets/zwtp.png');
        }
        setShowImageModal(true);
    };

    // 关闭图片预览
    const handleCloseImageModal = () => {
        setShowImageModal(false);
        setPreviewImageUrl('');
    };

    // 渲染搜索区域
    const renderSearchArea = () => (
        <View style={styles.searchContainer}>
            <View style={styles.searchRow}>
                {/* 工单号输入框 */}
                <View style={styles.searchItem}>
                    <Text style={styles.searchLabel1}>工单号</Text>
                    <View style={styles.searchInputContainer}>
                        <Image source={require('../../../../assets/ss.png')} style={styles.searchIcon} />
                        <TextInput
                            style={styles.searchInput}
                            value={searchParams.work_order_num}
                            onChangeText={(text) => setSearchParams(prev => ({ ...prev, work_order_num: text }))}
                            placeholder="请输入工单号"
                            placeholderTextColor="#999"
                        />
                    </View>
                </View>

                {/* 开始日期选择器 */}
                <View style={styles.searchItem}>
                    <Text style={styles.searchLabel}>开始日期</Text>
                    <DatePicker
                        value={startDate}
                        onChange={setStartDate}
                        format="YYYY-MM-DD"
                    >
                        <TouchableOpacity style={styles.dateSelector}>
                            <Text style={styles.dateText}>
                                {startDate ? formatDate(startDate) : '选择日期'}
                            </Text>
                        </TouchableOpacity>
                    </DatePicker>
                </View>

                {/* 结束日期选择器 */}
                <View style={styles.searchItem}>
                    <Text style={styles.searchLabel}>结束日期</Text>
                    <DatePicker
                        value={endDate}
                        onChange={setEndDate}
                        format="YYYY-MM-DD"
                    >
                        <TouchableOpacity style={styles.dateSelector}>
                            <Text style={styles.dateText}>
                                {endDate ? formatDate(endDate) : '选择日期'}
                            </Text>
                        </TouchableOpacity>
                    </DatePicker>
                </View>

                {/* 状态下拉框 */}
                <View style={styles.searchItem}>
                    <Text style={styles.searchLabel2}>状态</Text>
                    <View style={styles.stateDropdownContainer}>
                        <TouchableOpacity
                            ref={stateTriggerRef}
                            style={styles.stateSelector}
                            onPress={toggleStateDropdown}
                        >
                            <Text style={styles.stateText}>
                                {getStateDisplayText()}
                            </Text>
                            <Animated.Image
                                source={require('../../../../assets/xiala.png')}
                                style={[
                                    styles.arrowIcon,
                                    {
                                        transform: [{
                                            rotate: stateArrowRotation.interpolate({
                                                inputRange: [0, 1],
                                                outputRange: ['0deg', '180deg']
                                            })
                                        }]
                                    }
                                ]}
                            />
                        </TouchableOpacity>
                        <PortalDropdown
                            visible={stateDropdownVisible}
                            onClose={() => {
                                setStateDropdownVisible(false);
                                // 关闭时重置动画
                                Animated.timing(stateArrowRotation, {
                                    toValue: 0,
                                    duration: 200,
                                    useNativeDriver: true,
                                }).start();
                            }}
                            options={stateOptions}
                            selectedValues={selectedState ? [selectedState] : []}
                            onSelect={(value) => {
                                setSelectedState(value);
                                setStateDropdownVisible(false);
                                // 关闭时重置动画
                                Animated.timing(stateArrowRotation, {
                                    toValue: 0,
                                    duration: 200,
                                    useNativeDriver: true,
                                }).start();
                            }}
                            triggerRef={stateTriggerRef}
                            placeholder="状态"
                            multiple={false}
                        />
                    </View>
                </View>

                {/* 搜索和重置按钮 */}
                <View style={styles.buttonRow}>
                    <TouchableOpacity style={styles.searchButton} onPress={handleSearch}>
                        <Text style={styles.searchButtonText}>搜索</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.resetButton} onPress={handleReset}>
                        <Text style={styles.resetButtonText}>重置</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
    );

    // 渲染表格
    const renderTable = () => (
        <View style={styles.tableContainer}>
            <View style={styles.tableHeader}>
                <Text style={styles.tableHeaderCellLarge}>工单号</Text>
                <Text style={styles.tableHeaderCellLarge}>批次号</Text>
                <Text style={styles.tableHeaderCellExtraLarge}>产品名称</Text>
                <Text style={styles.tableHeaderCellSmall}>产品型号</Text>
                <Text style={styles.tableHeaderCellLarge}>规格</Text>
                <Text style={styles.tableHeaderCellLarge}>产品编码</Text>
                <Text style={styles.tableHeaderCell}>产品图片</Text>
                <Text style={styles.tableHeaderCellSmall}>工艺</Text>
                <Text style={styles.tableHeaderCellExtraLarge}>派工开始时间</Text>
                <Text style={styles.tableHeaderCellExtraLarge}>派工结束时间</Text>
                <Text style={styles.tableHeaderCellSmall}>数量</Text>
                <Text style={[styles.tableHeaderCellSmall, { borderRightWidth: 0 }]}>状态</Text>
            </View>
            <ScrollView style={styles.tableBody}>
                {loading ? (
                    <View style={styles.loadingContainer}>
                        <Text style={styles.loadingText}>加载中...</Text>
                    </View>
                ) : taskRecords.length === 0 ? (
                    <View style={styles.noDataContainer}>
                        <Text style={styles.noDataText}>暂无数据</Text>
                    </View>
                ) : (
                    taskRecords.map((item, index) => (
                        <View key={item.id || index} style={styles.tableRow}>
                            <Text style={styles.tableCellLarge}>{item.work_order_num || '-'}</Text>
                            <Text style={styles.tableCellLarge}>{item.batch_order_num || '-'}</Text>
                            <Text style={styles.tableCellExtraLarge}>{item.product_short_name || '-'}</Text>
                            <Text style={styles.tableCellSmall}>{item.product_model || '-'}</Text>
                            <Text style={styles.tableCellLarge}>{item.product_specs || '-'}</Text>
                            <Text style={styles.tableCellLarge}>{item.product_encode || '-'}</Text>
                            <TouchableOpacity
                                style={styles.tableCell}
                                onPress={() => handlePreviewImage(item.product_link)}
                            >
                                <Text style={{ color: '#1890ff', fontSize: 12 }}>查看图片</Text>
                            </TouchableOpacity>
                            <Text style={styles.tableCellSmall}>{item.process_name || '-'}</Text>
                            <Text style={styles.tableCellExtraLarge}>{item.work_start || '-'}</Text>
                            <Text style={styles.tableCellExtraLarge}>{item.work_end || '-'}</Text>
                            <Text style={styles.tableCellSmall}>{item.quantity || 0}</Text>
                            <Text style={[styles.tableCellSmall, { borderRightWidth: 0 }]}>
                                {getStateText(item.state)}
                            </Text>
                        </View>
                    ))
                )}
            </ScrollView>
        </View>
    );

    // 渲染分页
    const renderPagination = () => {
        const totalPages = pagination.pages;
        if (totalPages <= 1) return null;

        const pages = [];
        const currentPage = pagination.current;

        // 显示页码按钮
        for (let i = 1; i <= totalPages; i++) {
            if (
                i === 1 || // 第一页
                i === totalPages || // 最后一页
                (i >= currentPage - 1 && i <= currentPage + 1) // 当前页附近的页码
            ) {
                pages.push(
                    <TouchableOpacity
                        key={i}
                        style={[
                            styles.pageButton,
                            i === currentPage && styles.pageButtonActive
                        ]}
                        onPress={() => handlePageChange(i)}
                    >
                        <Text style={[
                            styles.pageButtonText,
                            i === currentPage && styles.pageButtonTextActive
                        ]}>
                            {i}
                        </Text>
                    </TouchableOpacity>
                );
            } else if (i === currentPage - 2 || i === currentPage + 2) {
                pages.push(
                    <Text key={i} style={styles.pageEllipsis}>...</Text>
                );
            }
        }

        return (
            <View style={styles.paginationContainer}>
                <TouchableOpacity
                    style={[
                        styles.pageButton,
                        currentPage === 1 && styles.pageButtonDisabled
                    ]}
                    onPress={() => currentPage > 1 && handlePageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                >
                    <Text style={[
                        styles.pageButtonText,
                        currentPage === 1 && styles.pageButtonTextDisabled
                    ]}>
                        上一页
                    </Text>
                </TouchableOpacity>

                {pages}

                <TouchableOpacity
                    style={[
                        styles.pageButton,
                        currentPage === totalPages && styles.pageButtonDisabled
                    ]}
                    onPress={() => currentPage < totalPages && handlePageChange(currentPage + 1)}
                    disabled={currentPage === totalPages}
                >
                    <Text style={[
                        styles.pageButtonText,
                        currentPage === totalPages && styles.pageButtonTextDisabled
                    ]}>
                        下一页
                    </Text>
                </TouchableOpacity>

                {/* 显示总条数信息 */}
                <Text style={styles.totalInfoText}>共 {pagination.total} 条</Text>
            </View>
        );
    };

    // 渲染图片预览模态框
    const renderImageModal = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={showImageModal}
                onRequestClose={handleCloseImageModal}
            >
                <View style={{
                    flex: 1,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>
                    <TouchableOpacity
                        style={{
                            flex: 1,
                            justifyContent: 'center',
                            alignItems: 'center',
                            width: '100%'
                        }}
                        onPress={handleCloseImageModal}
                        activeOpacity={1}
                    >
                        <Image
                            source={
                                previewImageUrl.startsWith('http') || previewImageUrl.startsWith('file://')
                                    ? { uri: previewImageUrl }
                                    : require('../../../../assets/zwtp.png')
                            }
                            style={{
                                width: '80%',
                                height: '60%',
                                resizeMode: 'contain'
                            }}
                        />
                        <TouchableOpacity
                            style={{
                                position: 'absolute',
                                top: 50,
                                right: 20,
                                width: 40,
                                height: 40,
                                backgroundColor: 'rgba(255, 255, 255, 0.8)',
                                borderRadius: 20,
                                justifyContent: 'center',
                                alignItems: 'center'
                            }}
                            onPress={handleCloseImageModal}
                        >
                            <Text style={{ fontSize: 24, color: '#333' }}>×</Text>
                        </TouchableOpacity>
                    </TouchableOpacity>
                </View>
            </Modal>
        );
    };



    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.header}>
                <Image
                    source={require('../../../../assets/terminal/home-header.png')}
                    style={styles.headerBackground}
                    resizeMode="cover"
                />
                <View style={styles.headerContent}>
                    <Text style={styles.headerText}>
                        MES终端服务系统
                    </Text>
                </View>
                <TouchableOpacity
                    style={styles.backButton}
                    onPress={onBackPress}
                >
                    <Image source={require('../../../../assets/fanhui.png')} style={styles.backIcon} />
                </TouchableOpacity>
            </View>

            <View style={styles.content}>
                {/* 搜索区域 */}
                {renderSearchArea()}

                {/* 表格区域 */}
                {renderTable()}

                {/* 分页区域 */}
                {renderPagination()}
            </View>

            {/* 图片预览模态框 */}
            {renderImageModal()}
        </SafeAreaView>
    );
};

export default ProductionTasks;